const {
  convertCloudUrlAsync
} = require('../../../utils/util');
import {
  getCurrentUserId
} from '../../../utils/user-helper.js';
import {
  checkAuthOnPageLoad
} from '../../../utils/auth.js';

Page({
  data: {
    pageTitle: '横屏|白底映彩类',
    taskType: '横屏|白底映彩类',
    isSubmitting: false,
    isTopicFocused: false,
    
    // 视频相关
    exampleVideoUrl: 'static/videos/彩色动画背景纯白.mp4',
    videoError: false,

    formData: {
      content: '',
      topic: '',
      times: '',
      material: '', // 默认选择阿基米德
      speaker: '',
      
    },

  },

  onTopicFocus() {
    this.setData({
      isTopicFocused: true
    });
  },
  onTopicBlur() {
    this.setData({
      isTopicFocused: false
    });
  },

  onLoad(options) {
    console.log('页面加载:', options);

    // 初始化视频播放器
    this.videoContext = wx.createVideoContext('exampleVideo');
  },


  // 主题词输入
  onTopicInput(e) {
    this.setData({
      'formData.topic': e.detail.value.slice(0, 25)
    });
  },
  // 视频错误处理
  onVideoError(e) {
    console.error('视频加载错误:', e.detail);
    this.setData({
      videoError: true
    });
  },

  // 视频加载成功
  onVideoLoad(e) {
    console.log('视频加载成功:', e.detail);
    this.setData({
      videoError: false
    });
  },

  // 预览设置
  onPreview() {
    const {
      formData,
    } = this.data;

    const previewData = {
      '主题词': formData.topic || '未填写',
    };

    let content = '';
    Object.keys(previewData).forEach(key => {
      content += `${key}: ${previewData[key]}\n`;
    });

    wx.showModal({
      title: '预览设置',
      content: content.trim(),
      showCancel: false,
      confirmText: '知道了'
    });
  },

  // 表单验证
  validateForm() {
    const {
      formData
    } = this.data;

    if (!formData.topic.trim()) {
      wx.showToast({
        title: '请输入主题词',
        icon: 'error'
      });
      return false;
    }

    if (formData.topic.length < 4) {
      wx.showToast({
        title: '主题词至少4个字',
        icon: 'error'
      });
      return false;
    }
    return true;
  },

  // 提交任务
  async onSubmit() {
    if (!this.validateForm()) return;

    if (this.data.isSubmitting) return;

    this.setData({
      isSubmitting: true
    });
    wx.showLoading({
      title: '提交中...'
    });

    try {
      // 获取当前用户ID
      const userId = getCurrentUserId();
      if (!userId) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }

      // 根据内容类型构建提交数据
      const submitData = {
        taskType: this.data.taskType,
        topic: this.data.formData.topic,
        content: this.data.formData.content,
        speaker: this.data.formData.speaker,
        material: this.data.formData.material,
        times: this.data.formData.times,
        style: this.data.formData.style,
        issubtitle: this.data.formData.issubtitle || 'true'
      };

      console.log(submitData)

      const result = await wx.cloud.callFunction({
        name: 'video-task',
        data: {
          action: 'submit',
          userId: userId, // 传入用户ID
          data: submitData
        },
        timeout: 60000 // 设置60秒超时
      });

      if (result.result.success) {
        wx.hideLoading();
        wx.showToast({
          title: '任务已提交',
          icon: 'success',
          duration: 2000
        });

        // 使用setTimeout延迟显示modal，避免与toast冲突导致卡顿
        setTimeout(() => {
          wx.showModal({
            title: '提交成功',
            content: '视频生成任务已提交，正在后台处理中...\n\n预计需要1-3分钟完成，您可以在任务列表中查看处理进度',
            showCancel: true,
            cancelText: '继续创建',
            confirmText: '查看任务',
            success: (res) => {
              if (res.confirm) {
                // 先显示加载提示，然后再跳转
                wx.showLoading({
                  title: '跳转中...',
                  mask: true
                });

                // 使用setTimeout延迟跳转，让loading先显示
                setTimeout(() => {
                  const taskId = result.result.data.taskId;
                  if (taskId) {
                    // 使用redirectTo避免页面栈过深，直接替换当前页面
                    wx.redirectTo({
                      url: `/packageTask/pages/task-detail/index?taskId=${taskId}&from=submit`,
                      success: () => {
                        wx.hideLoading();
                      },
                      fail: () => {
                        wx.hideLoading();
                        wx.showToast({
                          title: '跳转失败',
                          icon: 'none'
                        });
                      }
                    });
                  } else {
                    wx.switchTab({
                      url: '/pages/task-list/index',
                      success: () => {
                        wx.hideLoading();
                      },
                      fail: () => {
                        wx.hideLoading();
                        wx.showToast({
                          title: '跳转失败',
                          icon: 'none'
                        });
                      }
                    });
                  }
                }, 100);
              }
            }
          });
        }, 500);
      } else {
        // 检查是否是积分不足的错误
        if (result.result.code === 403 && result.result.message && result.result.message.includes('积分不足')) {
          wx.hideLoading();
          wx.showModal({
            title: '积分不足',
            content: result.result.message + '\n\n每次提交任务需要消耗1积分\n您可以联系客服充值积分',
            showCancel: true,
            cancelText: '查看积分',
            confirmText: '联系客服',
            success: (res) => {
              if (res.confirm) {
                // 跳转到客服页面或显示客服联系方式
                wx.showToast({
                  title: '请通过设置页面联系客服',
                  icon: 'none',
                  duration: 2000
                });
              } else {
                // 跳转到积分页面
                wx.navigateTo({
                  url: '/packageUser/pages/points/index'
                });
              }
            }
          });
          return;
        }
        throw new Error(result.result.error || result.result.message || '提交失败');
      }
    } catch (error) {
      console.error('提交任务失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: error.message || '提交失败',
        icon: 'error'
      });
    } finally {
      this.setData({
        isSubmitting: false
      });
    }
  },
});